#include "Sock.hpp"
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fstream>

#define WWWROOT "./wwwroot/"
#define HOME_PAGE "index.html"

void *handle(void *args)
{
    pthread_detach(pthread_self());
    int fd = *(int *)args;
    delete (int *)args;

// 定义一个缓冲区，作为输出型参数，获取client端写入的数据
#define SIZE 1024 * 10
    char buffer[SIZE];
    memset(buffer, 0, sizeof(buffer));
    ssize_t s = recv(fd, buffer, sizeof(buffer), 0);
    if (s > 0)
    {
        buffer[s] = 0;
        // 查看读取的请求
        std::cout << buffer;

        // 对客户端进行回应
        // 会获取报头中的method信息，此时将路径设为首页。

        string html_file = WWWROOT;
        html_file += HOME_PAGE;
        // if(method=='\') path=./index.html   //会获取报头中的method信息，此时将路径设为首页。
        struct stat st;
        stat(html_file.c_str(), &st);
        std::string http_response = "http/1.1 200 OK\n";
        http_response += "Content-Type:text/html;charset=utf8\n"; // text/plain,正文是普通的文本
        http_response += "Content-Length: ";
        http_response += to_string(st.st_size);
        http_response += "\n";
        http_response += "\n"; // 空行
        std::ifstream in(html_file);
        if (!in.is_open())
        {
            cerr << "open html error" << endl;
        }
        else
        {
            string content;
            string line;
            while (getline(in, line))
            {
                content += line;
            }
            http_response += content;
            in.close();
        }
        send(fd, http_response.c_str(), http_response.size(), 0);
        close(fd);
    }
}

int main(int args, char *argv[])
{
    if (args != 2)
    {
        return 1;
    }
    // 作为服务器端
    // 1.创建socket文件
    int Listen_fd = Socket::Sock();
    // 2.绑定IP和端口号
    Socket::Bind(Listen_fd, atoi(argv[1]));
    // 3.进行监听
    Socket::Listen(Listen_fd);
    // 4.持续的获取链接

    for (;;)
    {
        int newfd = Socket::Accept(Listen_fd);
        int *fd = new int(newfd);
        pthread_t pid;
        pthread_create(&pid, nullptr, handle, (void *)fd);
    }

    return 0;
}
